package com.itheima.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import com.itheima.mapper.UserMpper;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * @author Admin
 */
@Service
public class UserServiceImpl implements UserService {

         @Autowired
     private UserMpper userMpper;
    private ObjectMapper objectMapper;


    @Override
    public List<User> findAll() {
       return userMpper.selectList(null);
    }

    /**
     * id 查询
     * @param id
     * @return
     */
    @Override
    public User findById(long id) {

        return userMpper.selectById(id);
    }

      // 注入模板redis的类

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public List<User> findAllPlus() {

        List<User> userList = null;

        // 从redis中获取数据 尝试转换成json格式字符串

        String userListStr = stringRedisTemplate.opsForValue().get("user_List");
            ObjectMapper objectMapper = new ObjectMapper();
        if (userListStr !=null && !"".equals(userListStr)){
            System.out.println("从redis中获取数据");
            //  将从redis中查到的json数据转换成对集合传给controller
            try {
                // 这里不加引号第二次转换就是转换异常
                // com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'userListStr': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
                // at [Source: (String)"userListStr"; line: 1, column: 12]
             userList = objectMapper.readValue(userListStr, List.class);

                System.out.println("自己习惯了");
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else {
            try {
                System.out.println("从mysql中获取数据");
                userList = userMpper.selectList(null);
            // 将获取的数据转换成json
                userListStr = objectMapper.writeValueAsString(userList);
               // 存入redsi中
                stringRedisTemplate.opsForValue().set("user_List",userListStr);

            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
    return userList;
    }
}
